<template>
    <div style="width: 500px;background: #ffffff;">
        <el-form label-width="100">
            <el-form-item label="SSE服务地址">
                <el-input v-model="sseAddress" placeholder=""></el-input>
            </el-form-item>
            <el-form-item label="SSE请求响应">
                <el-input type="textarea" v-model="text" :rows="20" placeholder=""></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="send">发送</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
const sseAddress = ref('/api/demoSse/mvcSse');
const text = ref('');

const emitSourceRef = ref(null);

const send = () => {

    if (!sseAddress.value) {
        ElMessage.warning('请输入地址');
        return;
    }
    fetchSSE(sseAddress.value, (message) => {
        text.value = text.value + message + '\n';
    },()=>{
        console.log('完成');
    }).then();
};

async function fetchSSE(url, onmessage, oncomplete) {
    const response = await fetch(url, {
        method: 'GET',
        headers: {
            Accept: 'text/event-stream',
        },
    });

    if (!response.ok) {
        throw new Error(`HTTP 错误！状态码: ${response.status}`);
    }

    const reader = response.body.getReader();
    const decoder = new TextDecoder('utf-8');
    let buffer = '';
    while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        buffer += decoder.decode(value, { stream: true });

        let lines = buffer.split('\n');
        buffer = lines.pop(); // 保留未完成的部分

        for (const line of lines) {
            if (line.startsWith('data:')) {
                // console.log('收到数据:', line.slice(5).trim());
                let data = line.slice(5).trim();
                if (data === '[DONE]') {
                    // console.log('完成');
                    break;
                }
                onmessage(data);
            }
        }
    }
    oncomplete();
}
</script>